package com.ssyc.gsk_teacher_appraisal.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.ssyc.common.adapter.VpCommonAdapter;
import com.ssyc.common.base.BaseActivity;
import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.base.Constants;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.bean.ResultInfo;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.manager.MediaPlayerManager;
import com.ssyc.common.manager.PopUpManager;
import com.ssyc.common.manager.TimerCountManager;
import com.ssyc.common.utils.AlertDialogUtil;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.SPUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.MyGridView;
import com.ssyc.common.view.ZzHorizontalProgressBar;
import com.ssyc.common.view.dialog.CustomDialogManager;
import com.ssyc.common.view.vp.SuperViewPager;
import com.ssyc.gsk_teacher_appraisal.R;
import com.ssyc.gsk_teacher_appraisal.adapter.PanelGvAdapter;
import com.ssyc.gsk_teacher_appraisal.bean.CommitAnswerInfo;
import com.ssyc.gsk_teacher_appraisal.bean.PanelInfo;
import com.ssyc.gsk_teacher_appraisal.bean.QuestionDetailsInfo;
import com.ssyc.gsk_teacher_appraisal.bean.QuestionInfo32;
import com.ssyc.gsk_teacher_appraisal.bean.QuestionInfo34;
import com.ssyc.gsk_teacher_appraisal.bean.QuestionList;
import com.ssyc.gsk_teacher_appraisal.constant.TeacherAppKeys;
import com.ssyc.gsk_teacher_appraisal.fragment.AppraisalChooseWordAppropriateFormGapFillingFragment;
import com.ssyc.gsk_teacher_appraisal.fragment.AppraisalChooseWordFillArticFragment;
import com.ssyc.gsk_teacher_appraisal.fragment.AppraisalClozeSingleChooseFragment;
import com.ssyc.gsk_teacher_appraisal.fragment.AppraisalGrammarSingleChooseFragment;
import com.ssyc.gsk_teacher_appraisal.fragment.AppraisalLinstenSingleChooseFragment;
import com.ssyc.gsk_teacher_appraisal.fragment.AppraisalListenMultipleChooseFragment;
import com.ssyc.gsk_teacher_appraisal.fragment.AppraisalReadFragment;
import com.ssyc.gsk_teacher_appraisal.fragment.AppraisalTranslateSingleChooseFragment;
import com.ssyc.gsk_teacher_appraisal.fragment.AppraisalVocabularySingleChoiceFragment;
import com.ssyc.gsk_teacher_appraisal.util.TimeCount;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.iwgang.countdownview.CountdownView;
import cn.iwgang.countdownview.DynamicConfig;
import okhttp3.Call;

/**
 * 测评端展示题目详情界面
 * Created by Administrator on 2018/10/24 0024.
 */

public class TkTeacherAppraisalQuestionActivity extends BaseActivity implements View.OnClickListener, ViewPager.OnPageChangeListener {

    //Vp滚动的标识
    public static final String VPSCOLL = "TKTEACHERAPPRAISALQUESTIONACTIVITYVPSCROLL";
    private ImageView ivBack;
    private RelativeLayout rlChooseNum;
    private RelativeLayout rlLoading;
    private RelativeLayout rlContent;
    private LinearLayout ll_timer;
    private RelativeLayout rl_more;
    //测评报告
    private ImageView lv_cpbg;

    //推送
    private ImageView lv_ts;

    //更多
    private ImageView lv_more;

    //倒计时控件
    private CountdownView timer;

    //进度条
    private ZzHorizontalProgressBar pb;

    //显示进度条的文本
    private TextView tvPb;

    private SuperViewPager vp;

    //填充的Fragment集合
    private List<Fragment> mFragments;
    //ViewPager的适配器
    private VpCommonAdapter adapter;

    //记录ViewPager的页面位置值
    private int currPos = 0;

    //控制顶部的答题面板是否可以点击的标识
    private boolean isArrowClick = false;

    //提交面板的数据模型
    private List<PanelInfo> panelInfos;

    //页面跳转过来的区分标识
    //类型区分 1老师查看全校成绩(34号接口) 2老师预览试卷(32号接口)  3老师查看某个学生的成绩和学生查看自己的成绩(34号接口)  4学生答题(32号接口)
    private int autherType = -1;

    //试卷的整体试题模型,内含考察维度等一系列
    private QuestionInfo32.DataBean data;

    //计时器
    private Chronometer chronometer;

    //是否需要重新计时的标识
    public static boolean isNeedCountTime = true;

    //提交时需要上传的tel,通过Intent传入
    private String tel;

    //请求当前页面数据的试卷ID值row_id
    private String row_id;

    //提交时的参数rowid值为上个页面的row_id2
    private String commitrowid;

    //老师端查看学生分析界面需要的rowID
    private String h5Rowid;

    //编码
    private String exam_id;
    //学校编码
    private String school_id;
    //老师
    private String teacher;
    //班级
    private String class_num;
    //学生手机
    private String student;
    //姓名
    private String name;
    //用户角色
    private String role;
    //答题时间
    private int time;
    //套题名称
    private String testName;
    //是否显示更多按钮
    private String isShowMore;
    //单元+试卷名称
    private String rangetag;

    //套题标题
    private TextView tv_test_name;

    //提醒时间
    private int warningtime;

    //设置isNeedCountTime的方法
    public static void setIsNeedCountTime(boolean isNeedCountTime) {
        TkTeacherAppraisalQuestionActivity.isNeedCountTime = isNeedCountTime;
    }

    //提供给获取计时器控件的方法
    public Chronometer getTimer() {
        return chronometer;
    }

    public void setTimer(Chronometer chronometer) {
        this.chronometer = chronometer;
    }

    {
        //初始化计时器
        TimeCount.init();
    }

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    protected int getContentLayout() {
        return R.layout.activity_teacher_app_question;
    }

    @Override
    protected void init() {

        showContent();

        //接收数据
        initIntent();

        //初始化视图
        initView();

        //根据角色进入该页面同步视图状态
        sysViewState();



    }

    /**
     * 初始化视图
     */
    private void initView() {
        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        timer = findViewById(R.id.downtimer);
        rlChooseNum = findViewById(R.id.rl_choose_num);
        rlChooseNum.setOnClickListener(this);
        vp = findViewById(R.id.vp);
        rlLoading = findViewById(R.id.rl_loading);
        rlLoading.setVisibility(View.VISIBLE);
        pb = findViewById(R.id.pb);
        tvPb = findViewById(R.id.tv_pb);
        rlContent = findViewById(R.id.rl_content);
        rlContent.setVisibility(View.GONE);
        ll_timer = findViewById(R.id.ll_timer);
        rl_more = findViewById(R.id.rl_more);
        lv_cpbg = findViewById(R.id.lv_cpbg);
        lv_ts = findViewById(R.id.lv_ts);
        lv_more = findViewById(R.id.lv_more);
        tv_test_name = findViewById(R.id.tv_test_name);
        tv_test_name.setText(testName);
    }

    /**
     * 接收数据
     */
    private void initIntent() {

        //获取进入该页面的类型角色类型状态
        autherType = SPUtil.getInt(this, TeacherAppKeys.AUTHERTYPE);

        //获取传递的值
        tel = AccountUtils.getAccount(this);
        role = AccountUtils.getRole(this);
        if ("0".equals(role)) {
            //学生端通过Intent传递过来
            class_num = getIntent().getStringExtra("class_num");
        } else {
            //老师端从SP取class_num
            class_num = SPUtil.getString(this, "classnum");
        }

        row_id = getIntent().getStringExtra("rowId");
        commitrowid = getIntent().getStringExtra("commitrowid");
        exam_id = getIntent().getStringExtra("exam_id");
        school_id = getIntent().getStringExtra("school_id");
        student = getIntent().getStringExtra("student");
        name = getIntent().getStringExtra("name");
        teacher = getIntent().getStringExtra("teacher");

        testName = getIntent().getStringExtra("testName");
        isShowMore = getIntent().getStringExtra("isShowMore");
        rangetag = getIntent().getStringExtra("rangetag");

        h5Rowid = getIntent().getStringExtra("h5rowid");

        time = getIntent().getIntExtra("time", 25 * 60 * 1000);

        warningtime = time - (3 * 60 * 1000);

    }

    /**
     * 根据角色进入该页面同步视图状态
     */
    private void sysViewState() {

        if (autherType == 4) {
            //学生答题需要先弹框提示用户点击确定按钮后开始请求服务器数据

            //不显示倒计时
            ll_timer.setVisibility(View.GONE);

            //标题栏下部右边按钮图片不显示
            rl_more.setVisibility(View.GONE);

            //弹出提示语的Dialog
            showReminderDiglog();

        } else {
            //不显示倒计时控件
            ll_timer.setVisibility(View.GONE);
            //标题栏下部右边按钮图片不显示
            rl_more.setVisibility(View.VISIBLE);
            if (autherType == 1) {
                //老师查看全校试卷,更多显示,测评报告和推送按钮不显示
                lv_more.setVisibility(View.VISIBLE);
                lv_more.setOnClickListener(this);
                lv_cpbg.setVisibility(View.GONE);
                lv_ts.setVisibility(View.GONE);

            } else if (autherType == 2) {
                //老师预览试卷,推送按钮显示,测评报告和更多不显示
                lv_cpbg.setVisibility(View.GONE);
                if ("1".equals(isShowMore)) {
                    lv_ts.setVisibility(View.GONE);
                    lv_more.setVisibility(View.VISIBLE);
                    lv_more.setOnClickListener(this);
                } else {
                    lv_ts.setVisibility(View.VISIBLE);
                    lv_ts.setOnClickListener(this);
                    lv_more.setVisibility(View.GONE);
                }
            } else if (autherType == 3) {
                //老师查看学生成绩(学生查看自己成绩),测评报告显示,推送和更多不显示
                lv_cpbg.setVisibility(View.VISIBLE);
                lv_cpbg.setOnClickListener(this);
                lv_ts.setVisibility(View.GONE);
                lv_more.setVisibility(View.GONE);
                if("2".equals(role)){
                    //所选学生的姓名
                    tv_test_name.setText(name);
                }

            }

            //请求数据
            http();
        }
    }

    /**
     * 学生端做题时进入弹出的提示性Dialog
     */
    private void showReminderDiglog() {

        AlertDialogUtil.showAlertDialog(false, this, "考试开始后请不要退出答题界面或者关闭手机，请在规定时间内完成答题并提交，点击确定后将开始考试", new AlertDialogUtil.onListener() {
            @Override
            public void onClickOk() {

                http();
            }

            @Override
            public void onClickDismiss() {
                finish();
            }
        });
    }

    /**
     * 初始化倒计时控件
     */
    private void initDownTime() {
        timer.start(time);
        timer.setOnCountdownEndListener(new CountdownView.OnCountdownEndListener() {
            @Override
            public void onEnd(CountdownView cv) {
                //倒计时结束的监听事件
                //计时控件停止计时
                TimerCountManager.stopTimer(chronometer);
                //弹出强制提交的PopUpWindow
                showCoercivenessPop();
            }
        });


        timer.setOnCountdownIntervalListener(warningtime, new CountdownView.OnCountdownIntervalListener() {

            @Override
            public void onInterval(CountdownView cv, long remainTime) {
                DynamicConfig.Builder builder = new DynamicConfig.Builder();
                builder.setTimeTextColor(getResources().getColor(R.color.red));
                timer.dynamicShow(builder.build());
            }
        });
    }

    /**
     * 这里有几种状态
     * 教师端:1:已考试 2:未考试 (教师端都不可操作所有页面)
     * 学生端:考试状态,显示倒计时控件(可交互页面)
     */
    private void http() {

        Map<String, String> map = new HashMap<>();
        if (autherType == 4 || autherType == 2) {
            //老师预览试卷和学生答题请求32号接口
            map.put("type", "32");
            map.put("tel", tel);
            map.put("role", role);//用户角色
            map.put("rowId", row_id);
            if (autherType == 4) {
                map.put("exam_id", exam_id);
            }
        } else if (autherType == 1 || autherType == 3) {
            //老师查看全校成绩,老师查看某个学生的成绩,学生查看自己成绩
            map.put("type", "34");
            if (TextUtils.isEmpty(student)) {
                map.put("tel", tel);
                map.put("role", role);//0学生  2老师
            } else {
                //老师查看某个学生
                map.put("tel", student);
                map.put("role", "0");//0学生  2老师
            }

            map.put("rowId", row_id);
            map.put("exam_id", exam_id);
            map.put("school", school_id);//0学生  2老师

        }


        LogUtils.iTag("test", "查看单个学生：" +"type=34&tel="+tel+"&role=0&rowId="+
                row_id+"&exam_id="+exam_id+"&school="+school_id);

        HttpUtils.post(HttpAdress.APPTEST, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (null != rlLoading) {
                    rlLoading.setVisibility(View.GONE);
                }
                UiUtils.Toast("网络错误", false);
            }

            @Override
            public void onResponse(String response, int id) {

                if (rlLoading != null && rlLoading.getVisibility() == View.VISIBLE) {
                    rlLoading.setVisibility(View.GONE);
                }

                if (!TextUtils.isEmpty(response)) {
                    if (autherType == 4 || autherType == 2) {
                        //老师预览试卷和学生答题请求32号接口

                        //请求32号接口
                        QuestionInfo32 info = null;

                        try {
                            info = GsonUtil.jsonToBean(response, QuestionInfo32.class);
                        } catch (Exception e) {
                            Log.i("test", Constants.PARSEDATAERROR);
                        }


                        if (null != info) {
                            if ("200".equals(info.getState())) {
                                //返回成功
                                data = info.getData();

                                //发送消息
                                BusInfo busInfo = new BusInfo();
                                busInfo.msg = TkStudentrAppraisalMainActivity.UPDATEPAGEDATA;
                                EventBus.getDefault().post(busInfo);

                                if (data != null) {

                                    //显示页面数据
                                    if (rlContent != null && rlContent.getVisibility() != View.VISIBLE) {
                                        rlContent.setVisibility(View.VISIBLE);
                                    }

                                    if (autherType == 4) {
                                        //学生端答题请求成功后显示计时器并且开始计时
                                        ll_timer.setVisibility(View.VISIBLE);
                                        initDownTime();
                                    }

                                    //获取所有题型集合的Json字符串
                                    String questionJson = data.getContent();
                                    if (!TextUtils.isEmpty(questionJson)) {
                                        List<QuestionDetailsInfo> questionDetailsInfos = GsonUtil.jsonToList(questionJson, QuestionDetailsInfo[].class);
                                        if (questionDetailsInfos != null && questionDetailsInfos.size() != 0) {

                                            //初始化所有Framgent集合
                                            initFragments(questionDetailsInfos);

                                            //初始化提交面板的数据
                                            initPanelInfos(questionDetailsInfos);

                                        }
                                    }
                                }
                            } else if ("-1".equals(info.getState())) {
                                UiUtils.Toast("服务器异常,异常码:" + info.getState(), false);
                            } else if ("102".equals(info.getState())) {
                                UiUtils.Toast("无该试卷" + info.getState(), false);
                            }
                        }

                    } else if (autherType == 1 || autherType == 3) {
                        //老师查看全校成绩,老师查看某个学生的成绩和学生查看自己成绩 是一种状态
                        //请求34号接口
                        QuestionInfo34 info = null;
                        try {
                            info = GsonUtil.jsonToBean(response, QuestionInfo34.class);
                        } catch (Exception e) {
                            Log.i("test", Constants.PARSEDATAERROR);
                        }


                        LogUtils.iTag("test", "查看单个学生：" + response);

                        if (null != info) {
                            if ("200".equals(info.getState())) {
                                //返回成功
                                List<QuestionDetailsInfo> questionDetailsInfos = info.getData();

                                //初始化所有Framgent集合
                                initFragments(questionDetailsInfos);

                                //初始化提交面板的数据
                                initPanelInfos(questionDetailsInfos);

                            } else if ("-1".equals(info.getState())) {
                                UiUtils.Toast("服务器异常,异常码:" + info.getState(), false);
                            } else if ("102".equals(info.getState())) {
                                UiUtils.Toast("无该试卷" + info.getState(), false);
                            }
                        }
                    }
                }
            }
        });
    }

    /**
     * 根据返回的所有题型来创建Fragement
     */

    private void initFragments(List<QuestionDetailsInfo> infos) {

        mFragments = new ArrayList<>();

        for (int i = 0; i < infos.size(); i++) {
            if ("1".equals(infos.get(i).getTypeid())) {
                //添加听力单题单选
                mFragments.add(AppraisalLinstenSingleChooseFragment.newInstance(infos.get(i)));
            } else if ("2".equals(infos.get(i).getTypeid())) {
                //添加听力多题单选
                mFragments.add(AppraisalListenMultipleChooseFragment.newInstance(infos.get(i)));
            } else if ("3".equals(infos.get(i).getTypeid())) {
                //添加词汇单选
                mFragments.add(AppraisalVocabularySingleChoiceFragment.newInstance(infos.get(i)));
            } else if ("4".equals(infos.get(i).getTypeid())) {
                //添加语法单选
                mFragments.add(AppraisalGrammarSingleChooseFragment.newInstance(infos.get(i)));
            } else if ("5".equals(infos.get(i).getTypeid())) {
                //添加翻译单选
                mFragments.add(AppraisalTranslateSingleChooseFragment.newInstance(infos.get(i)));
            } else if ("6".equals(infos.get(i).getTypeid())) {
                //添加阅读单选(多题单选)
                mFragments.add(AppraisalReadFragment.newInstance(infos.get(i)));
            } else if ("7".equals(infos.get(i).getTypeid())) {
                //添加完型单选(多题单选)
                mFragments.add(AppraisalClozeSingleChooseFragment.newInstance(infos.get(i)));
            } else if ("8".equals(infos.get(i).getTypeid())) {
                //所给词适当形式填空单选
                mFragments.add(AppraisalChooseWordAppropriateFormGapFillingFragment.newInstance(infos.get(i)));
            } else if ("9".equals(infos.get(i).getTypeid())) {
                //选词填空
                mFragments.add(AppraisalChooseWordFillArticFragment.newInstance(infos.get(i)));
            }
        }

        //初始化Vp的操作
        if (mFragments.size() != 0) {

            //设置默认进度条的值
            pb.setProgress((int) ((float) (1) / (float) (mFragments.size()) * 100));

            //设置当前展示的Vp的页码
            tvPb.setText("1/" + (mFragments.size()));

            initVp();

            //设置Vp的监听
            vp.addOnPageChangeListener(this);

            rlContent.setVisibility(View.VISIBLE);
        }
        rlLoading.setVisibility(View.GONE);
    }

    /**
     * 根据服务器返回的数据来初始化提交面板的数据
     */
    public void initPanelInfos(List<QuestionDetailsInfo> questionDetailsInfos) {
        panelInfos = new ArrayList<>();
        for (int i = 0; i < questionDetailsInfos.size(); i++) {
            PanelInfo panelInfo = new PanelInfo();
            if (4 == autherType) {
                //学生端未考试
                //大题的题目编号
                panelInfo.question_id = questionDetailsInfos.get(i).getTypeid() + "";
                //答题的题目类型(单题单选,单题多选,阅读等具体的题型名称)
                panelInfo.question_type = questionDetailsInfos.get(i).getTitle_type() + "";
                //未考试都是未完成的状态
                panelInfo.state = 0;
                //未考试给0,检查大题的所有小题,如果所有小题都回答正确,该值给1,如果所有小题有一个题,则该值给0
                panelInfo.qa_answer = 0;

                //创建大题对应的提交信息
                List<CommitAnswerInfo> commitAnswerInfos = new ArrayList<>();

                //获取所有大题对应的小题集合
                List<QuestionDetailsInfo.SubListBean> sub_list = questionDetailsInfos.get(i).getSub_list();

                //组装每个大题对应的小题的提交数据模型
                if (null != sub_list && sub_list.size() != 0) {
                    for (int j = 0; j < sub_list.size(); j++) {
                        CommitAnswerInfo info = new CommitAnswerInfo();
                        //是否正确
                        info.isRight = false;
                        //编号
                        info.num = j + "";
                        //每小题的分数
                        info.score = Integer.parseInt(sub_list.get(j).getScore());
                        //正确答案
                        info.rightAnser = sub_list.get(j).getOption();
                        //自己的答案,默认是空
                        info.onwAnswer = "";
                        //词汇维度
                        info.r_word = sub_list.get(j).getR_word();
                        //句型结构维度
                        info.r_structure = sub_list.get(j).getR_structure();
                        //语法维度
                        info.r_grammar = sub_list.get(j).getR_grammar();
                        //阅读维度
                        info.r_read = sub_list.get(j).getR_read();
                        //交际功能维度
                        info.r_friend = sub_list.get(j).getR_friend();
                        //题目序号
                        info.id_D = sub_list.get(j).getId_D();

                        commitAnswerInfos.add(info);
                    }
                }

                //将大题对应的提交信息放入大题对应的数据模型中
                panelInfo.commitAnswerInfos = commitAnswerInfos;
                panelInfos.add(panelInfo);

            } else if (3 == autherType) {
                //老师端预览试卷
                panelInfo.state = 0;
                panelInfos.add(panelInfo);
            } else if (2 == autherType) {
                //老师端查看某个学生的成绩
                if (hasDownOver(questionDetailsInfos.get(i).getSub_list())) {
                    panelInfo.state = 1;
                } else {
                    panelInfo.state = 0;
                }
                panelInfos.add(panelInfo);
            } else if (1 == autherType) {
                //老师端查看全学校的成绩,全部灰色显示
                panelInfo.state = 0;
                panelInfos.add(panelInfo);
            }
        }

        //面板数据加载完成后可以点击
        isArrowClick = true;
    }


    /**
     * 根据每个大题的所有小题来判断该题是否作答
     */
    private boolean hasDownOver(List<QuestionDetailsInfo.SubListBean> subListBeans) {
        boolean res = true;
        for (int i = 0; i < subListBeans.size(); i++) {
            if (TextUtils.isEmpty(subListBeans.get(i).getStudent_option())) {
                //为空,表示该小题没有做
                res = false;
                break;
            }
        }
        return res;
    }

    /**
     * 初始化Vp的操作
     */
    private void initVp() {
        adapter = new VpCommonAdapter(getSupportFragmentManager(), mFragments);
        vp.setAdapter(adapter);
        vp.setOffscreenPageLimit(mFragments.size());
    }

    /**
     * 点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            //返回
            finish();
        } else if (id == R.id.rl_choose_num) {
            if (isArrowClick) {
                //弹出选择题目的PopWindow
                showAnswerQuestionPop();
            } else {
                UiUtils.Toast("正在加载数据,请稍候...", false);
            }
        } else if (id == R.id.lv_more) {
            //更多的点击事件
            showAnalyzePop();
        } else if (id == R.id.lv_cpbg) {
            //测评报告(跳转到学生试卷分析界面)
            if ("0".equals(role)) {
                //学生端
                TkStudentTestPaperAnalyzeActivity.startActivity(this, exam_id, school_id, teacher, tel, class_num, h5Rowid, name, rangetag);
            } else if ("2".equals(role)) {
                //教师端
                TkStudentTestPaperAnalyzeActivity.startActivity(this, exam_id, school_id, tel, student, class_num, h5Rowid, name, rangetag);
            }

        } else if (id == R.id.lv_ts) {
            //推送按钮
            Intent intent = new Intent(this, TkTeacherAppraisalTestReleaseActivity.class);
            intent.putExtra("rowId", row_id);
            intent.putExtra("testName", testName);
            startActivity(intent);
        }
    }

    /**
     * 点击更多弹出试卷整体分情况,学生分析的Pop
     */
    private void showAnalyzePop() {
        PopUpManager.showPop(this, R.layout.teacher_app_pop_analyze, 0.3f, new PopUpManager.onGetViewListener() {
            @Override
            public void getChildView(View view, int layoutResId) {
                //试卷整体情况
                TextView tvSjztfx = view.findViewById(R.id.tv_sjztqk);
                //学生分析
                TextView tvXsfx = view.findViewById(R.id.tv_xsfx);
                //取消
                TextView tvQx = view.findViewById(R.id.tv_qx);
                tvSjztfx.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        PopUpManager.dismiss();
                        //跳转到试卷分析界面
                        TkTeacherAppraisalTestPaperActivity.startActivity(TkTeacherAppraisalQuestionActivity.this, exam_id, school_id, tel, class_num, row_id);
                    }
                });

                tvXsfx.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        PopUpManager.dismiss();
                        //跳转到学生分析界面
                        TkTeacherAppStudentAnalyzeActivity.startActivity(TkTeacherAppraisalQuestionActivity.this, tel, exam_id);
                    }
                });

                tvQx.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        PopUpManager.dismiss();
                    }
                });
            }
        });
    }


    /**
     * 显示提交面板的PopUpwindow
     */
    private void showAnswerQuestionPop() {
        PopUpManager.showPop(this, R.layout.teacher_class_commit_answer, 0.3f, new PopUpManager.onGetViewListener() {
            @Override
            public void getChildView(View view, int layoutResId) {
                MyGridView mGv = view.findViewById(R.id.gv);
                Button btCommit = view.findViewById(R.id.bt_commit);
                //老师角色这里不显示提交按钮,学生角色根据是否是考试还是查看试卷来显示提交按钮
                if (4 == autherType) {
                    //学生
                    btCommit.setVisibility(View.VISIBLE);
                } else {
                    //老师
                    btCommit.setVisibility(View.GONE);
                }

                PanelGvAdapter panelGvAdapter = new PanelGvAdapter(TkTeacherAppraisalQuestionActivity.this, panelInfos, R.layout.teacher_class_gv_item_panel);
                mGv.setAdapter(panelGvAdapter);
                panelGvAdapter.setOnTvClickListener(new PanelGvAdapter.onTvClickListener() {
                    @Override
                    public void onClick(int pos) {
                        //关闭弹框
                        PopUpManager.dismiss();
                        //回调位置,Vp跳转到相对应的点击位置
                        currPos = pos;
                        vp.setCurrentItem(currPos);
                    }
                });

                btCommit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //提交按钮
                        //先判断是否允许提交的条件,测评端不做完题可以提交
                        if (!hasDoneOver(panelInfos)) {
                            PopUpManager.dismiss();
                            AlertDialogUtil.showAlertDialogTitle(TkTeacherAppraisalQuestionActivity.this,
                                    "是否交卷?", "交卷确认", new AlertDialogUtil.onClickListener() {
                                        @Override
                                        public void onClickOk() {
                                            //提交服务器
                                            doCommitAction();
                                        }
                                    });
                        } else {
                            PopUpManager.dismiss();
                            //提交服务器
                            doCommitAction();
                        }
                    }
                });
            }
        });
    }

    /**
     * 答题时间完毕后强制提交面板
     */
    private void showCoercivenessPop() {
        // 创建构建器
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(false);
        builder.setTitle("交卷确认")
                .setMessage("考试时间已到,是否交卷？如果选择不交卷，本次测试将无效，且如果需要再次测试，需要联系老师授权")
                .setNegativeButton("不交卷", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        finish();
                    }
                })
                .setPositiveButton("交卷", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog,
                                        int which) {
                        //做提交操作
                        doCommitAction();
                    }
                });
        builder.create().show();
    }


    /**
     * 提交服务器的方法
     */
    private void doCommitAction() {
        //上传给服务器的提交JSON对象
        QuestionList postInfo = new QuestionList();
        //试卷ID值,界面跳转的时候携带过来
        postInfo.setRow_id(commitrowid);
        //编码
        postInfo.setExam_id(exam_id);
        //学校编码
        postInfo.setSchool_id(school_id);
        //老师手机
        postInfo.setTeacher(teacher);
        //班级
        postInfo.setClass_num(class_num);
        //学生手机
        postInfo.setStudent(tel);
        //学生姓名
        postInfo.setName(AccountUtils.getName(this));
        //做题时长,这里需要判断做题的时间是否大于考试的时间
        postInfo.setTime(getPostTime());
        //做题的分数
        postInfo.setScore(getTotalScore(panelInfos));
        //试卷的总分数
        postInfo.setScore_percen(getAllScore(panelInfos) + "");

        List<QuestionList.WorkBean> workBeans = new ArrayList<>();
        for (int i = 0; i < panelInfos.size(); i++) {
            PanelInfo info = panelInfos.get(i);
            for (int j = 0; j < info.commitAnswerInfos.size(); j++) {

                //创建每个小题对应的服务器需要上传的数据模型
                QuestionList.WorkBean workBean = new QuestionList.WorkBean();

                //赋值几个维度值
                workBean.setR_friend(info.commitAnswerInfos.get(j).r_friend);
                workBean.setR_grammar(info.commitAnswerInfos.get(j).r_grammar);
                workBean.setR_read(info.commitAnswerInfos.get(j).r_read);
                workBean.setR_structure(info.commitAnswerInfos.get(j).r_structure);
                workBean.setR_word(info.commitAnswerInfos.get(j).r_word);

                //赋值number,如果该题型是单题,赋值0,如果该题型多题,赋值从1开始到小题的数量结束
                if (info.commitAnswerInfos.size() == 1) {
                    //证明该题型只有1个小题
                    workBean.setNumber("0");
                } else if (info.commitAnswerInfos.size() > 1) {
                    //证明该题型有多个小题
                    workBean.setNumber((j + 1) + "");
                }

                //题型,也就是服务器返回的每个大题对应的typeid
                workBean.setTypeid(info.question_id);

                //每个小题的题目序号
                workBean.setId_D(info.commitAnswerInfos.get(j).id_D);

                //每个小题的分数
                workBean.setScore(info.commitAnswerInfos.get(j).score + "");

                //大题回答是否正确0错误 1正确  大题只有0 和1(小题都作答正确 该答题传1  否则传0(小题没做和错误的情况))
                if (isAllRight(info.commitAnswerInfos)) {
                    workBean.setQa_answer("1");
                } else {
                    workBean.setQa_answer("0");
                }

                //小题回答是否正确0错误 1正确 -1表示没有作答
                if (info.commitAnswerInfos.get(j).isRight) {
                    workBean.setSub_answer("1");
                } else {
                    if (TextUtils.isEmpty(info.commitAnswerInfos.get(j).onwAnswer)) {
                        //表示没有作答
                        workBean.setSub_answer("-1");
                    } else {
                        //作答了但是不正确
                        workBean.setSub_answer("0");
                    }
                }

                //设置每道小题的作答
                if (TextUtils.isEmpty(info.commitAnswerInfos.get(j).onwAnswer)) {
                    workBean.setOption_content("");
                } else {
                    workBean.setOption_content(info.commitAnswerInfos.get(j).onwAnswer);
                }

                workBeans.add(workBean);
            }
        }

        postInfo.setWork(workBeans);

        //上传的json数据
        String postJson = GsonUtil.objectToJson(postInfo);

        LogUtils.iTag("test", "测评提交"+postJson);

        CustomDialogManager.show(TkTeacherAppraisalQuestionActivity.this, "提交中...");
        Map<String, String> map = new HashMap<>();
        map.put("type", "33");
        map.put("tel", tel);
        map.put("question_list", postJson);

        LogUtils.iTag("test","提交的参数是:"+"type=33&tel="+tel+"&question_list="+postJson);

        HttpUtils.post(HttpAdress.CPCOMMIT, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                CustomDialogManager.dissmiss();
                UiUtils.Toast(BaseApplication.ERROR, false);
            }

            @Override
            public void onResponse(String response, int id) {
                CustomDialogManager.dissmiss();
                ResultInfo info = null;
                if (!TextUtils.isEmpty(response)) {
                    try {
                        info = GsonUtil.jsonToBean(response, ResultInfo.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    if (info != null) {
                        if ("200".equals(info.state)) {
                            //上传成功
                            UiUtils.Toast("提交成功", false);
                            //发送消息
                            BusInfo busInfo = new BusInfo();
                            busInfo.msg = TkStudentrAppraisalMainActivity.UPDATEPAGEDATA;
                            EventBus.getDefault().post(busInfo);
                            //关闭页面
                            finish();
                        } else {
                            UiUtils.Toast("提交失败,错误码是:" + info.state, false);
                            Log.i("test", "错误码是:" + info.state);
                        }
                    }
                }
            }
        });
    }

    /**
     * 获取试卷总分数的方法
     *
     * @param panelInfos
     * @return
     */
    private int getAllScore(List<PanelInfo> panelInfos) {
        int res = 0;
        for (int i = 0; i < panelInfos.size(); i++) {
            List<CommitAnswerInfo> commitAnswerInfos = panelInfos.get(i).commitAnswerInfos;
            for (int j = 0; j < commitAnswerInfos.size(); j++) {
                res += commitAnswerInfos.get(j).score;
            }
        }
        return res;
    }


    /**
     * Vp的选中事件
     *
     * @param position
     * @param positionOffset
     * @param positionOffsetPixels
     */
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        //记录当前ViewPager的位置
        currPos = position;

        //设置进度条的文本显示值
        tvPb.setText((position + 1) + "/" + (mFragments.size()));

        //同时需要设置进度条的值
        pb.setProgress((int) ((float) (position + 1) / (float) (mFragments.size()) * 100));

        //翻页的时候需要发出翻页的消息,在听力选择界面进行播放器的状态同步
        BusInfo info = new BusInfo();
        info.vpScoll = VPSCOLL;
        EventBus.getDefault().post(info);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }


    /**
     * 判断所有大题是否做完的方法
     */
    public boolean hasDoneOver(List<PanelInfo> panelInfos) {
        boolean res = true;
        for (int i = 0; i < panelInfos.size(); i++) {
            if (panelInfos.get(i).state == 0) {
                res = false;
                break;
            }
        }
        return res;
    }

    /**
     * 获取上传的时间的方法,返回的是秒
     */
    public String getPostTime() {

        //获取上传时间
        long useTime = TimeCount.newInstance().getTotalTime() + (System.currentTimeMillis() - TimeCount.newInstance().getLastTime());

        //转化为秒
        String seconds = useTime / 1000 + "";

        return seconds;
    }

    /**
     * 获取上传的总分数的方法
     * 上传的key为score
     */
    public String getTotalScore(List<PanelInfo> panelInfos) {
        int res = 0;
        for (int i = 0; i < panelInfos.size(); i++) {
            res += panelInfos.get(i).score;
        }
        return res + "";
    }

    /**
     * 考虑熄屏
     */
    @Override
    protected void onPause() {
        super.onPause();

        TimerCountManager.stopTimer(chronometer);

        long time = System.currentTimeMillis() - TimeCount.newInstance().getLastTime();

        //计算总用时
        long totalTime = TimeCount.newInstance().getTotalTime() + time;

        //记录总用时
        TimeCount.newInstance().setTotalTime(totalTime);
    }

    /**
     * 考虑亮屏
     */
    @Override
    protected void onRestart() {
        super.onRestart();

        if (isNeedCountTime) {
            TimerCountManager.startTimer(false, chronometer);
        }

        //重置LastTime
        TimeCount.newInstance().setLastTime(System.currentTimeMillis());
    }

    /**
     * 生命周期中停止计时
     */
    @Override
    protected void onDestroy() {


        //销毁时停止计时
        TimerCountManager.stopTimer(chronometer);

        //还原状态
        setIsNeedCountTime(true);

        //还原计时器的时间统计
        TimeCount.release();

        //如果音频还在播放
        MediaPlayerManager.getInstance().stop();

        super.onDestroy();
    }

    /**
     * EventBus的处理事件的方法
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);
        if (null != busInfo && busInfo.tkMsg == TeacherAppKeys.TKMsg) {
            //取出当前Vp所在的页面的大题对象
            PanelInfo info = panelInfos.get(currPos);
            List<CommitAnswerInfo> commitAnswerInfos = info.commitAnswerInfos;
            //取出作答的小题对象,同步当前小题的作答信息
            int pos = busInfo.tkChoosePos;
            CommitAnswerInfo answerInfo = commitAnswerInfos.get(pos);
            answerInfo.onwAnswer = busInfo.tkChooseAnswer;
            answerInfo.isRight = busInfo.tkChooseResult;

            //同步info的状态
            //是否完成的状态同步
            if (hasCompeted(commitAnswerInfos)) {
                //已经做完
                info.state = 1;
            } else {
                //没有做完
                info.state = 0;
            }

            //总分的状态同步
            info.score = getScore(commitAnswerInfos);

            //是否正确的状态同步qa_answer的值
            if (isAllRight(commitAnswerInfos)) {
                info.qa_answer = 1;
            } else {
                info.qa_answer = 0;
            }

            //同步大题中每个小题的正确率
            info.sub_answer = sysSubAnswer(commitAnswerInfos);

            //同步大题中每个小题的具体答案
            info.option_content = sysOptionContent(commitAnswerInfos);
        } else if (busInfo != null && TkTeacherAppraisalMainActivity.CPUPDATEPAGEDATA.equals(busInfo.msg)) {
            //提交成功关闭
            finish();
        }
    }

    /**
     * 根据小题是否都作答判断该答题是否做完的方法
     * 返回true做完,返回false没做完
     * 只要小题中onwAnswer有一个是空,则返回false
     */
    public boolean hasCompeted(List<CommitAnswerInfo> commitAnswerInfos) {
        boolean res = true;
        for (int i = 0; i < commitAnswerInfos.size(); i++) {
            if (TextUtils.isEmpty(commitAnswerInfos.get(i).onwAnswer)) {
                res = false;
                break;
            }
        }
        return res;
    }

    /**
     * 根绝每个小题返回当前答题的分数
     * 先判断当前小题是否作答正确,如果正确,则加上该小题的分数
     */
    public int getScore(List<CommitAnswerInfo> commitAnswerInfos) {
        int res = 0;
        for (int i = 0; i < commitAnswerInfos.size(); i++) {
            if (commitAnswerInfos.get(i).isRight) {
                //作答正确
                res += commitAnswerInfos.get(i).score;
            }
        }
        return res;
    }

    /**
     * 根据小题是否都正确来判断该大题是否正确的方法
     * 返回true全部正确,返回false则错误
     * 只要小题中onwAnswer有一个是空,则返回false
     */
    public boolean isAllRight(List<CommitAnswerInfo> commitAnswerInfos) {
        boolean res = true;
        for (int i = 0; i < commitAnswerInfos.size(); i++) {
            if (!commitAnswerInfos.get(i).isRight) {
                res = false;
                break;
            }
        }
        return res;
    }

    /**
     * 同步大题中每个小题的对错的方法
     * 将每个小题的用户的作答对错使用￠连接拼串
     */
    public String sysSubAnswer(List<CommitAnswerInfo> commitAnswerInfos) {
        String res = "";
        for (int i = 0; i < commitAnswerInfos.size(); i++) {
            if (i == 0) {
                //第一个
                if (commitAnswerInfos.get(i).isRight) {
                    res += "1";
                } else {
                    res += "0";
                }
            } else {
                //其它,使用￠+当前自己的作答进行连接
                if (commitAnswerInfos.get(i).isRight) {
                    res += "￠" + "1";
                } else {
                    res += "￠" + "0";
                }
            }
        }
        return res;
    }

    /**
     * 同步大题中每个小题的具体答案的方法
     * 将每个小题的用户自己作答的信息使用￠连接拼串
     */
    public String sysOptionContent(List<CommitAnswerInfo> commitAnswerInfos) {
        String res = "";
        for (int i = 0; i < commitAnswerInfos.size(); i++) {
            if (i == 0) {
                //第一个
                res += commitAnswerInfos.get(i).onwAnswer;
            } else {
                //其它,使用￠+当前自己的作答进行连接
                res += "￠" + commitAnswerInfos.get(i).onwAnswer;
            }
        }
        return res;
    }
}